package com.cg.offer;

import com.cg.leetcode.TreeNode;
import org.junit.Test;

import java.util.*;

/**
 * 剑指Offer 32-I.从上到下打印二叉树
 *
 * @program: LeetCode->Offer_32_I
 * @description: 剑指Offer 32-I.从上到下打印二叉树
 * @author: cg
 * @create: 2022-03-14 15:57
 **/
public class Offer_32_I {

    @Test
    public void test32() {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(Arrays.toString(levelOrder(root)));
    }

    /**
     * 从上到下打印出二叉树的每个节点，同一层的节点按照从左到右的顺序打印。
     * <p>
     * 例如:
     * 给定二叉树: [3,9,20,null,null,15,7],
     *    3
     *   / \
     *  9  20
     *    /  \
     *   15   7
     * 返回：
     * [3,9,20,15,7]
     * <p>
     * 提示：
     * 节点总数 <= 1000
     *
     * @param root
     * @return
     */
    public int[] levelOrder(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return new int[0];
        }
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            list.add(node.val);
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
        }
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }

}
